﻿using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.XtraEditors;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using OilDB;
using System.Windows.Forms;

namespace MainApp
{
    public partial class FrmMain : XtraForm
    {
        #region AutomaticSet
        private void SetGridDataSource()
        {
            gridCompanies.DataSource = data.DsOil;
            gridCompanies.DataMember = "Companies";

            //gridCustomers.DataSource = data.DsOil;
            //gridCustomers.DataMember = "Customers";
            gridCustomers.DataSource = bdsCustomers2;

            gridExpenses.DataSource = data.DsOil;
            gridExpenses.DataMember = "Expenses";

            gridImports.DataSource = data.DsOil;
            gridImports.DataMember = "Imports";

            gridPayments.DataSource = data.DsOil;
            gridPayments.DataMember = "Payments";

            //gridSells.DataSource = data.DsOil;
            //gridSells.DataMember = "Sells";

            gridProducts.DataSource = data.DsOil;
            gridProducts.DataMember = "Products";

            gridStores.DataSource = data.DsOil;
            gridStores.DataMember = "Stores";

            gridDebts.DataSource = data.DsOil;
            gridDebts.DataMember = "Debts";

            gridReceipts.DataSource = data.DsOil;
            gridReceipts.DataMember = "Receipts";

            gridDebtStatistics.DataSource = data.DsOil;
            gridDebtStatistics.DataMember = "DebtStatistics_All";

            gridDebtStatisticsCompany.DataSource = data.DsOil;
            gridDebtStatisticsCompany.DataMember = "DebtStatistics_Company";
        }

        private void SetBindingSource()
        {
            bdsCompanies.DataSource = data.DsOil;
            bdsCompanies.DataMember = "Companies";

            bdsCustomers.DataSource = data.DsOil;
            bdsCustomers.DataMember = "Customers";

            bdsProducts.DataSource = data.DsOil;
            bdsProducts.DataMember = "Products";

            bdsProductsFull.DataSource = data.DsOil;
            bdsProductsFull.DataMember = "Products";

            bdsStores.DataSource = data.DsOil;
            bdsStores.DataMember = "Stores";

            bdsCustomers2.DataSource = data.DsOil;
            bdsCustomers2.DataMember = "Customers";

            bdsHoaDonKhachHang.DataSource = data.DsOil;
            bdsHoaDonKhachHang.DataMember = "Receipts";



            //bdsCustomers2.Filter = "CustomerName <> 'Bán lẻ'";
            bdsCustomers2.Filter = String.Format("ID <> '{0}'", Guid.Empty);

        }

        private void SetRowUpdatedEvent()
        {
            gridViewImports.RowUpdated += gridView_RowUpdated;
            //gridViewSells.RowUpdated += gridView_RowUpdated;
            gridViewPayments.RowUpdated += gridView_RowUpdated;
            gridViewExpenses.RowUpdated += gridView_RowUpdated;
            gridViewCompanies.RowUpdated += gridView_RowUpdated;
            gridViewCustomers.RowUpdated += gridView_RowUpdated;
            gridViewStores.RowUpdated += gridView_RowUpdated;
            gridViewProducts.RowUpdated += gridView_RowUpdated;
            gridViewDebts.RowUpdated += gridView_RowUpdated;
        }

        //not done
        private void SetSomething()
        {
            //data.DsOil.Customers.DisplayExpression = "ID <> '00000000-0000-0000-0000-000000000000'";

        }
        #endregion

        private bool Login()
        {
            SqlConnectionStringBuilder cnStr = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["OilDB.Properties.Settings.OILManagementConnectionString"].ConnectionString);

            cnStr.IntegratedSecurity = false;
            using (LoginDialog fLogin = new LoginDialog())
            {
                using (SqlConnection test = new SqlConnection())
                {
                    bool loginOK = false;
                    while (!loginOK)
                    {
                        if (!fLogin.getLogin())
                        {
                            Application.ExitThread();
                            return false;
                        }
                        cnStr.UserID = fLogin.UserName;
                        cnStr.Password = fLogin.Password;
                        test.ConnectionString = cnStr.ConnectionString;
                        try
                        {
                            test.Open();
                            test.Close();
                            loginOK = true;
                        }
                        catch (Exception)
                        {
                            loginOK = false;
                            MessageBox.Show("Không thể đăng nhập", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    //cnStr.UserID = "sa";
                    //cnStr.Password = "queenphuong";
                }
            }
            mainConnection = new SqlConnection(cnStr.ConnectionString);
            data = new OilDB.DataServices(cnStr.ConnectionString, currentStore);
            //data.DsOil.DebtStatistics_All.DefaultView.Sort = "Debt";
            return true;
        }
        //checked
        private Guid GetStoreIDFromUser()
        {
            FrmGetStore tmp = new FrmGetStore(bdsStores);
            Guid store;
            if (tmp.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                store = tmp.GetStoreID();
                return store;
            }
            else
                return Guid.Empty;
        }
        //checked
        private bool PayDebts()
        {
            if (!(mainTabControl.SelectedTabPage == tabDebtStatistics))
            {
                XtraMessageBox.Show("Vui lòng chọn những món nợ muốn trả", "Thông báo", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                return false;
            }
            int[] index = gridViewDebtStatistics.GetSelectedRows();
            if (index.Length == 0)
            {
                //do nothing
                XtraMessageBox.Show("Vui lòng chọn những món nợ muốn trả", "Thông báo", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                return false;
            }
            else if (XtraMessageBox.Show("Trả những món nợ này?", "Xác nhận", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                Guid storeId;
                if (currentStore != Guid.Empty)
                    storeId = currentStore;
                else
                    storeId = GetStoreIDFromUser();
                if (storeId == Guid.Empty)
                {
                    //XtraMessageBox.Show("Vui lòng chọn cây xăng nhận tiền", "Cảnh báo", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    return false;
                }
                else
                {

                    for (int i = index.Length - 1; i >= 0; i--)
                    {
                        OilDB.DataSetOilManagement.DebtStatistics_AllRow row = gridViewDebtStatistics.GetDataRow(index[i]) as OilDB.DataSetOilManagement.DebtStatistics_AllRow;
                        OilDB.DataSetOilManagement.PaymentsRow newRow = data.DsOil.Payments.NewPaymentsRow();
                        newRow.ID = Guid.NewGuid();
                        newRow.StoreID = storeId;
                        newRow.Customer = row.Customer;
                        newRow.PayTime = DateTime.Now;
                        newRow.Amount = row.Debt;
                        newRow.Note = "Trả hết nợ trước ngày " + DateTime.Now.ToString("dd/MM/yyyy");
                        data.DsOil.Payments.AddPaymentsRow(newRow);
                        data.DsOil.DebtStatistics_All.RemoveDebtStatistics_AllRow(row);
                    }
                    return true;
                }
            }
            else
                return false;
        }

        private void InitControlProperties()
        {

            //gridViewStores.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
            //gridViewStores.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False;
            //gridViewStores.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;

            colStore.OptionsColumn.AllowEdit = false;
            //colStoreID1.OptionsColumn.AllowEdit = false;
            colStoreID2.OptionsColumn.AllowEdit = false;
            colStoreID3.OptionsColumn.AllowEdit = false;
            colStoreID4.OptionsColumn.AllowEdit = false;
            //colCommission.Visible = false;
            colCommission1.Visible = false;

            //btnStores.Enabled = false;
            //itemStores.Enabled = false;
            //tabStores.PageVisible = false;

            gridViewCompanies.OptionsBehavior.Editable = true;
            gridViewCompanies.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            gridViewCompanies.KeyDown += gridView_KeyDown;

            gridViewCustomers.OptionsBehavior.Editable = true;
            gridViewCustomers.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            gridViewCustomers.KeyDown += gridView_KeyDown;

            gridViewExpenses.OptionsBehavior.Editable = true;
            gridViewExpenses.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            gridViewExpenses.KeyDown += gridView_KeyDown;

            gridViewImports.OptionsBehavior.Editable = true;
            gridViewImports.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            gridViewImports.KeyDown += gridView_KeyDown;

            gridViewPayments.OptionsBehavior.Editable = true;
            gridViewPayments.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            gridViewPayments.KeyDown += gridView_KeyDown;

            gridViewDebts.OptionsBehavior.Editable = true;
            gridViewDebts.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            gridViewDebts.KeyDown += gridView_KeyDown;

            gridViewReceipts.OptionsBehavior.Editable = true;
            gridViewReceipts.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            gridViewReceipts.KeyDown += gridView_KeyDown;

            gridViewProducts.OptionsBehavior.Editable = false;

            //gridViewSells.OptionsBehavior.Editable = true;
            //gridViewSells.KeyDown += gridView_KeyDown;

            gridViewStores.OptionsBehavior.Editable = true;

            this.Text += ", " + LoadStoreName();
            curStore.EditValue = currentStore;
            curStore.Properties.ReadOnly = true;
        }

        private void LoadCurrentStore()
        {
            currentStore = global::MainApp.Properties.Settings.Default.storeid;
        }

        private void DoUndo()
        {
            if (XtraMessageBox.Show("Bạn muốn trả lại dữ liệu từ lần lưu gần nhất?", "Xác nhận", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                data.DsOil.RejectChanges();
                btnUndo.Enabled = false;
                btnSave.Enabled = false;
                data.UpdateStatistics(currentStore);
                inReport.UpdateReport();
                outReport.UpdateReport();
                cashReport.updateReport();
            }
        }

        private string LoadStoreName()
        {
            OilDB.DataSetOilManagement.StoresRow row = data.DsOil.Stores.FindByID(currentStore);
            return (string)row["StoreName"];
        }

        #region TabSells
        private List<Product_new> productList = new List<Product_new>();
        private OilDB.DataSetOilManagement.IndexForDispensersDataTable newIndex;

        private void InitTabSells()
        {
            btnSells_Cancel.Enabled = false;
            btnSells_OK.Enabled = false;
            newIndex = new OilDB.DataSetOilManagement.IndexForDispensersDataTable();
            curDate.EditValueChanged += new EventHandler(curDate_EditValueChanged);
            curDate.EditValueChanging += new DevExpress.XtraEditors.Controls.ChangingEventHandler(curDate_EditValueChanging);
            curDate.EditValue = DateTime.Now;
            if (currentStore != Guid.Empty)
            {
                btnSells_Cancel.Click += btnCancel_Click;
                btnSells_OK.Click += btnOK_Click;
            }            

            curStore.EditValueChanged += curDate_EditValueChanged;
        }

        void curDate_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            bool canEdit = currentStore != Guid.Empty;
            if (btnSells_Cancel.Enabled)
            {
                e.Cancel = true;
                return;
            }
            if (canEdit && btnSave.Enabled)
            {
                if (XtraMessageBox.Show("Dữ liệu có thay đổi. Lưu dữ liệu trước khi chuyển ngày hoặc dữ liệu trở về ban đầu", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                    btnSave_ItemClick(null, null);
                else
                {
                    data.DsOil.RejectChanges();
                    btnUndo.Enabled = false;
                    btnSave.Enabled = false;
                }
            }
        }

        void curDate_EditValueChanged(object sender, EventArgs e)
        {
            bool canEdit = currentStore != Guid.Empty;
            if (curStore.EditValue == null)
            {
                return;
            }            

            if (curDate.DateTime.Date > DateTime.Now.Date)
            {
                curDate.EditValue = DateTime.Now;
            }
            bool today = curDate.DateTime.Date == DateTime.Now.Date;

            decimal totalImport;
            data.IndexForDispensersAdapter.Fill(data.DsOil.IndexForDispensers, null, curDate.DateTime.Date);
            data.IndexForDispensersAdapter.Fill(newIndex, null, curDate.DateTime.Date.AddDays(1));
            data.ImportStatisticsAdapter.Fill(data.DsOil.ImportStatistics, null, curDate.DateTime.Date.AddDays(1));
            productList.Clear();
            pnlProducts.Controls.Clear();
            foreach (OilDB.DataSetOilManagement.ProductsRow row in data.DsOil.Products.Rows)
            {
                if (row.IsNull(data.DsOil.Products.TypeColumn))
                {
                    totalImport = GetTotalImport(row.ID);
                    Product_new tmp = new Product_new(row.ID, row.ProductName, totalImport, today, canEdit, GetPrice(row.ID, curDate.DateTime.Date));
                    tmp.ValueChanged += new EventHandler(productDispensers_ValueChanged);
                    tmp.AddNewClicked += new EventHandler(productDispensers_AddNewClicked);
                    tmp.DispenserDeleted += new EventHandler(productDispensers_DispenserDeleted);
                    tmp.Dock = DockStyle.Left;
                    pnlProducts.Controls.Add(tmp);
                    LoadDispensers(tmp, row.ID, today);
                    productList.Add(tmp); 
                }
            }
        }

        private decimal GetPrice(Guid product, DateTime date)
        {
            Dictionary<Guid, decimal> map = new Dictionary<Guid, decimal>();
            Guid currentStore = new Guid(curStore.EditValue.ToString());
            foreach (OilDB.DataSetOilManagement.SellsRow item in data.DsOil.Sells.Rows)
                if (item.SellTime == date)
                {
                    map.Add(item.Dispenser, item.Price);
                }
            foreach (OilDB.DataSetOilManagement.DispensersRow row in data.DsOil.Dispensers.Rows)
                if (row.Product == product && row.StoreID == currentStore && map.ContainsKey(row.ID))
                    return map[row.ID];
            foreach (OilDB.DataSetOilManagement.ProductsRow row in data.DsOil.Products.Rows)
                if (row.ID == product)
                {
                    return row.Price;
                }
            return 0;
        }

        private void LoadDispensers(Product_new product, Guid productid, bool today)
        {
            if (curStore.EditValue == null)
            {
                return;
            }
            Guid currentStore = new Guid(curStore.EditValue.ToString());
            foreach (OilDB.DataSetOilManagement.DispensersRow row in data.DsOil.Dispensers.Rows)
                if ((row.Active || !today) && row.Product == productid && row.StoreID == currentStore)
                {                   
                    OilDB.DataSetOilManagement.IndexForDispensersRow tmp = data.DsOil.IndexForDispensers.FindByID(row.ID);
                    OilDB.DataSetOilManagement.IndexForDispensersRow tmp2 = newIndex.FindByID(row.ID);
                    decimal index1 = tmp != null ? tmp.Index : 0;
                    decimal index2 = tmp != null ? tmp2.Index : 0;
                    product.AddDispenser(row.ID, row.Name, index1, index2);
                }
        }

        private decimal GetTotalImport(Guid product)
        {
            if (curStore.EditValue == null)
            {
                return 0;
            }
            Guid currentStore = new Guid(curStore.EditValue.ToString());
            OilDB.DataSetOilManagement.ImportStatisticsRow row = data.DsOil.ImportStatistics.FindByStoreIDProduct(currentStore, product);
            if (row != null)
                return row.TotalAmount;
            else
                return 0;
        }

        #region ControlOnTabEvents

        private void btnCancel_Click(object sender, EventArgs e)
        {
            data.DsOil.RejectChanges();
            btnSells_Cancel.Enabled = false;
            btnSells_OK.Enabled = false;
            curDate_EditValueChanged(null, null);
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (curStore.EditValue == null)
            {
                return;
            }
            Guid currentStore = new Guid(curStore.EditValue.ToString());
            foreach (Product_new product in productList)
            {
                foreach (Dispenser dispenser in product)
                {
                    if (dispenser.ChangedName)
                    {
                        OilDB.DataSetOilManagement.DispensersRow disRow = data.DsOil.Dispensers.FindByID(dispenser.ID);
                        disRow.Name = dispenser.DispenserName;
                    }

                    if (dispenser.TotalInput >= 0)
                    {
                        DataRow[] temp = data.DsOil.Sells.Select(String.Format("Dispenser = '{0}' AND (SellTime = '{1}')", dispenser.ID, curDate.DateTime.Date));
                        OilDB.DataSetOilManagement.SellsRow editRow;
                        decimal oldAmount;
                        if (temp.Length == 1)
                        {
                            editRow = temp[0] as OilDB.DataSetOilManagement.SellsRow;
                            oldAmount = editRow.Amount;
                        }
                        else if (temp.Length == 0)
                        {
                            //add new row
                            editRow = data.DsOil.Sells.NewSellsRow();
                            editRow.ID = Guid.NewGuid();
                            editRow.SellTime = curDate.DateTime.Date;
                            OilDB.DataSetOilManagement.ProductsRow row = data.DsOil.Products.FindByID(product.ProductID);
                            editRow.Price = row.Price;
                            editRow.Commission = row.Commission;
                            editRow.Dispenser = dispenser.ID;
                            oldAmount = 0;
                            editRow.Amount = 0;
                            data.DsOil.Sells.AddSellsRow(editRow);
                        }
                        else
                        {
                            throw new Exception("Duplicate");
                        }
                        editRow.Amount = dispenser.TotalInput;
                        editRow.Price = product.Price;

                        //update export statistics
                        OilDB.DataSetOilManagement.ExportStatisticsAllRow row2 = data.DsOil.ExportStatisticsAll.FindByProductStoreID(product.ProductID, currentStore);
                        if (row2 != null)
                        {
                            row2.TotalAmount += editRow.Amount - oldAmount;
                        }
                        else
                        {
                            data.DsOil.ExportStatisticsAll.AddExportStatisticsAllRow(currentStore, product.ProductID, editRow.Amount - oldAmount);
                        }
                    }
                }
            }
            btnSave.Enabled = true;
            btnUndo.Enabled = true;

            btnSells_OK.Enabled = false;
            btnSells_Cancel.Enabled = false;
        }
        #endregion

        #region ControlEvents
        void productDispensers_ValueChanged(object sender, EventArgs e)
        {
            bool valid = true;
            foreach (Product_new item in productList)
            {
                valid &= item.IsValid;
            }
            btnSells_OK.Enabled = valid;
            btnSells_Cancel.Enabled = true;
        }

        void productDispensers_AddNewClicked(object sender, EventArgs e)
        {
            if (curStore.EditValue == null)
            {
                return;
            }
            Guid currentStore = new Guid(curStore.EditValue.ToString());
            Product_new tmp = sender as Product_new;
            OilDB.DataSetOilManagement.DispensersRow newRow = data.DsOil.Dispensers.NewDispensersRow();
            newRow.ID = Guid.NewGuid();
            newRow.StoreID = currentStore;
            newRow.Product = tmp.ProductID;
            newRow.Name = "Vòi mới";
            //Get new name
            FrmGetName tmpDlg = new FrmGetName(newRow.Name);
            if (tmpDlg.ShowDialog() == DialogResult.OK)
            {
                newRow.Name = tmpDlg.GetName();
            }
            newRow.Active = true;

            FrmGetMeter meterDlg = new FrmGetMeter(0);
            if (meterDlg.ShowDialog() == DialogResult.OK)
            {
                decimal value = meterDlg.GetMeterValue();
                OilDB.DataSetOilManagement.ImportsRow importRow = data.DsOil.Imports.NewImportsRow();
                importRow.ID = newRow.ID;
                importRow.ImportTime = new DateTime(2011, 6, 30);
                importRow.StoreID = newRow.StoreID;
                importRow.Product = newRow.Product;
                importRow.Amount = value;
                importRow.Note = "";
                data.DsOil.Imports.AddImportsRow(importRow);

                OilDB.DataSetOilManagement.SellsRow sellRow = data.DsOil.Sells.NewSellsRow();
                sellRow.ID = newRow.ID;
                sellRow.SellTime = new DateTime(2011, 6, 30);
                sellRow.Amount = value;
                sellRow.Price = 0;
                sellRow.Commission = 0;
                sellRow.Note = "";
                sellRow.Dispenser = newRow.ID;
                data.DsOil.Sells.AddSellsRow(sellRow);
            }
            data.DsOil.Dispensers.AddDispensersRow(newRow);
            tmp.AddDispenser(newRow.ID, newRow.Name);
            data.DsOil.IndexForDispensers.AddIndexForDispensersRow(newRow.ID, 0);
            if (btnSells_Cancel.Enabled == false)
            {
                btnSells_OK.Enabled = true;
                btnSells_Cancel.Enabled = true;
            }            
        }

        void productDispensers_DispenserDeleted(object sender, EventArgs e)
        {
            Dispenser dispenser = sender as Dispenser;
            OilDB.DataSetOilManagement.DispensersRow row = data.DsOil.Dispensers.FindByID(dispenser.ID);
            row.Active = false;
            if (btnSells_Cancel.Enabled == false)
            {
                btnSells_OK.Enabled = true;
                btnSells_Cancel.Enabled = true;
            }
        }
        #endregion
        #endregion
    }
}
